<?php
namespace app\banquet\model;

use app\BaseModel;
use app\card\model\Company;
use app\card\model\User;
use app\member\model\Member;
use app\member\model\StoredOrder;
use app\publics\model\TmplConfig;
use app\shop\model\IndexCardCount;
use longbingcore\wxcore\WxTmpl;
use think\facade\Db;

class Order extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_banquet_order';


    protected $append = [

        'company_name',

        'content',

        'table_text'


    ];


    /**
     * @author chenniang
     * @DataTime: 2022-01-15 16:13
     * @功能说明:桌数拼接
     */
    public function getTableTextAttr($value,$data){

        if(isset($data['min_num'])&&isset($data['max_num'])){

            return $data['min_num'].'~'.$data['max_num'].'桌';

        }


    }

    /**
     * @author chenniang
     * @DataTime: 2022-01-14 11:38
     * @功能说明:报名信息
     */
    public function getContentAttr($value,$data){

        if(!empty($data['id'])){

            $order_content = new OrderContent();

            $list = $order_content->where(['order_id'=>$data['id']])->select()->toArray();

            return $list;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-07 17:46
     * @功能说明:查询公司名字
     */
    public function getCompanyNameAttr($value,$data){

        if(!empty($data['company_id'])){

            $company_model = new Company();

            $name = $company_model->where(['id'=>$data['company_id']])->value('name');

            return $name;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:00
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:03
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:04
     * @功能说明:详情
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:
     */
    public function dataList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-19 14:30
     * @功能说明:
     */
    public function adminList($dis,$page=10){

        $data = $this->alias('a')
                ->join('longbing_card_user_phone b','a.user_id = b.user_id','left')
                ->where($dis)
                ->field('a.*,b.phone')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 15:39
     * @功能说明:支付回调
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->dataInfo(['order_code'=>$order_code]);

        if(!empty($order)&&$order['pay_type']==1){

            $update = [

                'pay_time' => time(),

                'pay_type' => 2,

                'transaction_id' => $transaction_id
            ];

            Db::startTrans();

            $this->dataUpdate(['id'=>$order['id']],$update);
            //余额支付扣款
            $this->orderStoredResult($order);

            Db::commit();
            //给员工发送消息
            $this->payNoticeStaff($order);
            //给客户发送订阅消息
            $this->sendService($order);

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-17 10:19
     * @功能说明:储值支付回调
     */
    public function orderStoredResult($order,$type=9){
        //增加储值支付记录
        if($order['balance']>0){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $order['user_id'],'uniacid'=>$order['uniacid']]);

            $title  = $order['place_title'];

            $store_order_model = new StoredOrder();

            $stored = $order['balance'];
            //增加记录
            $store_order_model->desStore($stored,'',$member,$type,$order['staff_id'],$order['order_code'],$title);
        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2019-12-27 19:19
     * @功能说明:发送订阅消息
     */
    public function sendService($order){

        $user_model = new User();
        //获取用户的open_id
        $openid = $user_model->where(['id'=>$order['user_id']])->value('openid');

        $page = '/banquet/pages/order/detail?id='.$order['id'];
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where(['uniacid'=>$order['uniacid'],'tmpl_name'=>'banquet_order'])->find();
        //如果未添加模版消息 则不发送
        if(empty($tmpl)){
            return true;
        }else{
            $tmpl = $tmpl->toArray();
        }
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];
//        //模版类容
//        $key_worlds = $tmpl['kidList'];
        $service_model = new WxTmpl($order['uniacid']);
        //模版的key
        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){

            //验证模版内容
            if(!is_array($key_worlds)||count($key_worlds)<3){
                return true;
            }

            $company_model = new Company();

            $company_name = $company_model->where(['id'=>$order['company_id']])->value('name');
            //发送内容
            $send_data = array(
                $key_worlds[1]=>array(
                    //商品名称
                    'value'=>$order['place_title'],
                ),
                $key_worlds[2]=>array(

                    'value'=>date('Y-m-d',$order['time_date']),
                ),
                $key_worlds[3]=>array(

                    'value'=>$company_name,
                ),

            );
            //模版消息库类
            $tmpl_sever = new WxTmpl($order['uniacid']);
            //发送模版消息
            $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);

        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',1];

        $dis[] = ['over_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $order = $this->where($dis)->select()->toArray();

        if(!empty($order)){

            foreach ($order as $value){

                $this->dataUpdate(['id'=>$value['id']],['pay_type'=>-1,'cancel_time'=>$value['over_time']]);
            }
        }

        return true;
    }

    /**
     * User: chenniang
     * Date: 2019-09-10 15:14
     * @param $order
     * @param string $sign
     * @return bool
     * descption: 发送员工端消息
     */
    public function payNoticeStaff($order){

        $inset_data = [

            'user_id' => $order['user_id'],

            'to_uid'  => $order['staff_id'],

            'type'    => 683,

            'sign'    => 'view',

            'target'  => $order['id'],

            'uniacid' => $order['uniacid']

        ];

        $count_model = new IndexCardCount();

        $insert_id = $count_model->countAdd($inset_data);

        $push_data = array(

            'action'  => 'longbingSendWxServiceNotice',

            'event'   => 'longbingSendWxServiceNotice',

            'count_id'=> $insert_id
        );

        publisher(json_encode($push_data ,true));

        return true;
    }








}